import { Switch, message } from 'antd'
import { ControlType as TYPE } from "@components";
import { useMainContext } from '@contexts/MainContext'
import { useState } from 'react';
import { editCfgSwitch } from "@apis/autoConfigApi";

const fields = [
    { name:'unitCode', label:'归属机构', controlType:TYPE.SELECT, codeKey:'userAuthUnits'},
    { name:'switchStatus', label:'预警状态', controlType:TYPE.SELECT, codeKey:'EmerSwitchType'}
]

const MySwitch = ({unitCode, status}) => {
  const { isButtomShow } = useMainContext()
  const newStatus = status === 'open' ? true : false
  const [loading, setLoading] = useState(false)
  const [checked, setChecked] = useState(newStatus)
  const onClick = async (isChecked) => {
    setLoading(true)
    const {data, error} = await editCfgSwitch({unitCode, switchStatus: isChecked ? 'open' : 'close'})
    setLoading(false)
    if (error) return
    message.success(data)
    setChecked(isChecked)
  }
  return (
    <>
      <Switch checked={checked} loading={loading} onClick={onClick} size="default" disabled={!isButtomShow("430302")} />
    </>
  )
}

const GetColumns = () => {
  return [
    { title:'归属机构', dataIndex:'unitName', key:'unitName', open:true},
    { title: '开关状态', dataIndex: 'switchStatusName', key: 'switchStatusName', open: true ,
      render: (_, record) => <MySwitch unitCode={record.unitCode} status={record.switchStatus} />
    },
    { title:'更新时间', dataIndex:'updateTime', key:'updateTime', open:true},
  ]
}

export  { fields, GetColumns }